<template>
  <div class="class-form-container" v-loading="isLoading || isFetching">
    <el-page-header @back="goBack" :content="isEditMode ? '编辑班级' : '创建新班级'"></el-page-header>
    <el-divider></el-divider>

    <el-card shadow="never">
       <template #header>
           <div class="card-header">
             <span>班级信息</span>
           </div>
       </template>
      <el-form :model="classForm" :rules="rules" ref="classFormRef" label-width="100px">
        <el-form-item label="班级名称" prop="name">
          <el-input v-model="classForm.name" placeholder="请输入班级名称"></el-input>
        </el-form-item>
        <el-form-item label="课程名称" prop="course">
          <el-input v-model="classForm.course" placeholder="请输入课程名称"></el-input>
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-input v-model="classForm.grade" placeholder="请输入年级，如 高三、大二"></el-input>
        </el-form-item>
         <el-form-item label="班级容量" prop="capacity">
          <el-input-number v-model="classForm.capacity" :min="1" :max="200" placeholder="请输入班级容量"></el-input-number>
        </el-form-item>
         <el-form-item label="起止日期" prop="dateRange">
            <el-date-picker
              v-model="classForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DDTHH:mm:ss"
            />
          </el-form-item>
        <el-form-item label="班级描述" prop="description">
          <el-input
            type="textarea"
            :rows="4"
            v-model="classForm.description"
            placeholder="请输入班级描述信息"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="isLoading">
            {{ isEditMode ? '保存更新' : '立即创建' }}
          </el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue';
import { useStore } from 'vuex';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';

const store = useStore();
const router = useRouter();
const route = useRoute();

// --- 状态和计算属性 ---
const classFormRef = ref(null); // 表单引用
const isLoading = computed(() => store.state.class.isLoading); // Vuex loading
const isFetching = ref(false); // 用于加载编辑数据的 loading

const classForm = reactive({
  id: null,
  name: '',
  description: '',
  course: '',
  grade: '',
  startDate: null,
  endDate: null,
  capacity: 50,
  dateRange: [], // 用于 el-date-picker
});

// 判断是否为编辑模式
const isEditMode = computed(() => !!route.params.id);
const classId = computed(() => route.params.id);

// --- 表单验证规则 ---
const rules = reactive({
  name: [{ required: true, message: '请输入班级名称', trigger: 'blur' }],
  // 其他字段根据需要添加验证规则
});

// --- 方法 ---

// 获取班级详情 (编辑模式)
const fetchClassDetailsForEdit = async () => {
  if (!isEditMode.value) return;
  isFetching.value = true;
  // 先尝试从 store 获取，如果不存在再请求 API
  let currentDetail = store.getters['class/getCurrentClassDetail'];
  if (!currentDetail || currentDetail.id !== parseInt(classId.value)) {
      const result = await store.dispatch('class/fetchClassDetail', classId.value);
       if (!result.success) {
          isFetching.value = false;
          // 获取失败，跳转回列表页或其他处理
          router.push({ name: 'ClassList' });
          return;
       }
       currentDetail = result.data; // API 返回的数据结构可能需要调整
  }

   // 使用获取到的详情填充表单
  if(currentDetail) {
      classForm.id = currentDetail.id;
      classForm.name = currentDetail.name;
      classForm.description = currentDetail.description;
      classForm.course = currentDetail.course;
      classForm.grade = currentDetail.grade;
      classForm.capacity = currentDetail.capacity;
      classForm.startDate = currentDetail.startDate;
      classForm.endDate = currentDetail.endDate;
      // 设置日期范围选择器的值
      if(currentDetail.startDate && currentDetail.endDate) {
          classForm.dateRange = [currentDetail.startDate, currentDetail.endDate];
      } else {
          classForm.dateRange = [];
      }
  }
  isFetching.value = false;
};

// 提交表单
const handleSubmit = () => {
  classFormRef.value.validate(async (valid) => {
    if (valid) {
      // 从 dateRange 更新 startDate 和 endDate
      if (classForm.dateRange && classForm.dateRange.length === 2) {
          classForm.startDate = classForm.dateRange[0];
          classForm.endDate = classForm.dateRange[1];
      } else {
          classForm.startDate = null;
          classForm.endDate = null;
      }

      // 构造提交的数据，移除 dateRange
      // eslint-disable-next-line no-unused-vars
      const { dateRange, ...submitData } = classForm;

      let result;
      if (isEditMode.value) {
        result = await store.dispatch('class/updateClass', { id: classId.value, classData: submitData });
      } else {
        result = await store.dispatch('class/createClass', submitData);
      }

      if (result.success) {
        router.push({ name: 'ClassList' }); // 成功后返回列表页
      }
      // 失败消息已在 action 中处理
    } else {
      ElMessage.error('请检查表单输入');
      return false;
    }
  });
};

// 返回上一页
const goBack = () => {
  router.back();
};

// --- 生命周期和监听器 ---

// 监听路由参数变化，用于从创建页跳转到编辑页或反之 (虽然不常见，但保持健壮性)
watch(() => route.params.id, (newId, oldId) => {
    if (newId !== oldId) {
         if (newId) { // 进入编辑模式
             fetchClassDetailsForEdit();
         } else { // 进入创建模式，重置表单
             classFormRef.value?.resetFields(); // 重置验证状态
             Object.assign(classForm, { // 重置数据
                id: null, name: '', description: '', course: '', grade: '',
                startDate: null, endDate: null, capacity: 50, dateRange: [],
             });
         }
    }
}, { immediate: true }); // 立即执行一次，处理初始加载

</script>

<style scoped>
.class-form-container {
  padding: 20px;
}
.el-card {
    margin-top: 20px;
}
.el-page-header {
    margin-bottom: 20px;
}
.el-divider {
    margin: 20px 0;
}
</style> 